<template>
  <div v-if="show" class="network-dialog">
    <div class="dialog-content">
      <h3>网络对战</h3>
      <div v-if="!isConnected" class="connect-form">
        <input v-model="serverUrl" placeholder="服务器地址" />
        <button @click="handleConnect">连接</button>
      </div>
      <div v-else class="room-controls">
        <div v-if="!roomId">
          <button @click="handleCreateRoom">创建房间</button>
          <div class="join-room">
            <input v-model="joinRoomId" placeholder="房间ID" />
            <button @click="handleJoinRoom">加入房间</button>
          </div>
        </div>
        <div v-else class="room-info">
          <p>房间ID: {{ roomId }}</p>
          <p>您的颜色: {{ playerColor === 'white' ? '白方' : '黑方' }}</p>
          <button @click="handleLeaveRoom">离开房间</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useChessNetwork } from '../composables/useChessNetwork'

const props = defineProps<{
  show: boolean
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'joined', color: 'white' | 'black'): void
}>()

const {
  isConnected,
  roomId,
  playerColor,
  connect,
  createRoom,
  joinRoom,
  disconnect
} = useChessNetwork()

const serverUrl = ref('ws://localhost:3000')
const joinRoomId = ref('')

const handleConnect = () => {
  connect(serverUrl.value)
}

const handleCreateRoom = () => {
  createRoom()
}

const handleJoinRoom = () => {
  if (joinRoomId.value) {
    joinRoom(joinRoomId.value)
  }
}

const handleLeaveRoom = () => {
  disconnect()
  emit('close')
}

// 监听玩家颜色变化
watch(playerColor, (newColor: 'white' | 'black' | null) => {
  if (newColor) {
    emit('joined', newColor)
  }
})
</script>

<style scoped>
.network-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 300px;
}

.connect-form,
.room-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.join-room {
  display: flex;
  gap: 10px;
}

input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}
</style> 